package org.jeecg.modules.custom.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.RedisPublicKeyPrefixConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.custom.entity.MtCustomEquip;
import org.jeecg.modules.custom.entity.MtCustorm;
import org.jeecg.modules.custom.mapper.MtCustomEquipMapper;
import org.jeecg.modules.custom.mapper.MtCustormMapper;
import org.jeecg.modules.custom.service.IMtCustormService;
import org.jeecg.modules.station.service.IMtServiceStationService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

/**
 * @Description: 客户表
 * @Author: jeecg-boot
 * @Date:   2022-08-19
 * @Version: V1.0
 */
@Service
public class MtCustormServiceImpl extends ServiceImpl<MtCustormMapper, MtCustorm> implements IMtCustormService {

	private RedisUtil redisUtil;
	@Autowired
	private MtCustormMapper mtCustormMapper;
	@Autowired
	private MtCustomEquipMapper mtCustomEquipMapper;
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private IMtServiceStationService mtServiceStationService;

	public MtCustormServiceImpl(RedisUtil redisUtil) {
		this.redisUtil = redisUtil;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
		mtCustomEquipMapper.deleteByMainId(id);
		mtCustormMapper.deleteById(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			mtCustomEquipMapper.deleteByMainId(id.toString());
			mtCustormMapper.deleteById(id);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void allotBatchMain(Collection<? extends Serializable> idList, String providerId) {
		for(Serializable id:idList) {
			MtCustorm mtCustorm = new MtCustorm();
			mtCustorm.setId(id.toString());
			mtCustorm.setProviderId(providerId);
			mtCustorm.setStationId("");//清除已设置的服务站
			//处理客户设备
			List<MtCustomEquip> list = mtCustomEquipMapper.selectByMainId(id.toString());
			if(list!=null && list.size()>0)
			{
				for (MtCustomEquip mtCustomEquip:list) {
					if(mtCustomEquip!=null)
					{
						mtCustomEquip.setProviderId(providerId);
						mtCustomEquip.setStationId("");//清除已设置的服务站
						mtCustomEquipMapper.updateById(mtCustomEquip);
					}
				}
			}
			//处理客户
			mtCustormMapper.updateById(mtCustorm);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void allotStationBatchMain(Collection<? extends Serializable> idList, String StationId) {
		for(Serializable id:idList) {
			MtCustorm mtCustorm = new MtCustorm();
			mtCustorm.setId(id.toString());
			mtCustorm.setStationId(StationId);
			//处理客户设备
			List<MtCustomEquip> equipList = mtCustomEquipMapper.selectByMainId(id.toString());
			if(equipList!=null && equipList.size()>0)
			{
				for (MtCustomEquip mtCustomEquip:equipList) {
					if(mtCustomEquip!=null)
					{
						mtCustomEquip.setStationId(StationId);
						mtCustomEquipMapper.updateById(mtCustomEquip);
					}
				}
			}
			//处理客户
			mtCustormMapper.updateById(mtCustorm);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveUserAndRole(MtCustorm mtCustorm) {
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		//往user表中添加数据
		JSONObject user = new JSONObject();
		user.put("username", mtCustorm.getLinkPhone());//账号：客户手机号
		user.put("realname", mtCustorm.getCustormName());//用户名称：客户名称
		user.put("password", mtCustorm.getLinkPhone());//密码：客户手机号
		user.put("phone", mtCustorm.getLinkPhone());//手机号
		user.put("confirmpassword", mtCustorm.getLinkPhone());
		user.put("useridentity", 1);//身份（1 普通成员 2 上级）
		user.put("userId", mtCustorm.getLinkPhone());
		user.put("activitisync", 1);//同步工作流引擎(1-同步,0-不同步)
		user.put("contacts", mtCustorm.getCustormName());//联系人
		user.put("workNo", mtCustorm.getLinkPhone());//工号：手机号码
		user.put("usertype", 4);//0平台管理员 1服务商 2服务站 3工程师 4客户
		//插入到user表中，并设置角色
		Result<SysUser> userResult = sysUserService.addUserAndRoleOfCustom(user);
		redisUtil.removeAll(CacheConstant.SYS_DEPARTS_CACHE);
		redisUtil.removeAll(CacheConstant.SYS_DEPART_IDS_CACHE);
		if (!userResult.isSuccess()) {
			//报错，进行事务回滚
			throw new JeecgBootException(userResult.getMessage());
		}
		SysUser result = userResult.getResult();
		mtCustorm.setUserId(result.getUsername()); //账号绑定
		//往客户表里添加数据
		super.save(mtCustorm);
		// 更新用户关联id
		SysUser sysUser = new SysUser();
		sysUser.setId(result.getId())
				.setLinkId(mtCustorm.getId());
		sysUserService.updateById(sysUser);
		String jsonString = JSON.toJSONString(mtCustorm);
		redisUtil.set(RedisPublicKeyPrefixConstant.CUSTOM + ":" + mtCustorm.getSysOrgCode() + ":" + mtCustorm.getCreateBy(), jsonString, 60 * 60 * 2);
	}

}
